<template>
  <el-drawer direction="rtl" v-model="dialogVisible" :title="dialogTitle" size="1200px">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="授权方式">
          <dict-tag :type="DICT_TYPE.ADDR_AUTH_TYPE" :value="queryParams.authType" />
        </el-form-item>
        <el-form-item label="关键字" prop="keyWord">
          <el-input placeholder="区域名称" v-model.trim="queryParams.keyWord" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="addrId" width="60" />
        <el-table-column label="授权地址" align="left" prop="addrName" />
      </el-table>
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      <div style="clear: both">
        <el-row>
          <el-col :span="22">
            <el-form ref="formRef" :model="form">
              <el-input v-model="form.authUserId" :readonly="true" style="display: none" />
              <el-input v-model="form.authUserName" placeholder="请选择管理人员" :readonly="true">
                <template #append>
                  <el-button @click="openSelectMember()">小程序</el-button>
                  <el-button @click="openSelectSys()">管理员</el-button>
                  <el-button type="danger" @click="clearUser()">清空</el-button>
                </template>
              </el-input>
            </el-form>
          </el-col>
          <el-col :span="2">
            <el-button type="danger" @click="submitAuth">确 定</el-button>
          </el-col>
        </el-row>
      </div>
    </ContentWrap>
  </el-drawer>
  <MemberUserSelect ref="selectMemberRef" @confirm-member-user="confirmMemberUser" />
  <SysUserSelect ref="sysUserSelectRef" @confirm-sys-user="confirmSysUser" />
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import * as AuthAddrApi from '@/api/zwsj/authAddr'
import MemberUserSelect from '@/views/zwsj/common/MemberUserSelect.vue'
import SysUserSelect from '@/views/zwsj/common/SysUserSelect.vue'

defineOptions({ name: 'AuthAddrForm' })
const emits = defineEmits(['comfirmAuthAddr'])

const message = useMessage()
const { t } = useI18n()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref() // 列表的数据
const selectedRows = ref<AuthAddrApi.AuthAddrVo[]>([]) // 表的列表

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  authType: '',
  keyWord: undefined
})

/** 打开弹窗 */
const form = ref({
  authType: '',
  userType: undefined,
  authUserId: undefined,
  authUserName: undefined,
  authAddrIds: []
})
const open = async (authType: string) => {
  dialogVisible.value = true
  dialogTitle.value = '授权'

  queryParams.authType = authType
  resetForm()
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const queryFormRef = ref() // 搜索的表单

/** 重置表单 */
const formRef = ref() // 表单 Ref
const resetForm = () => {
  form.value = {
    authType: undefined,
    userType: undefined,
    authUserId: undefined,
    authUserName: undefined,
    authAddrIds: []
  } as any
  formRef.value?.resetFields()
}

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.keyWord = queryParams.keyWord || ''
    const data = await AuthAddrApi.getAuthAddrPageByAuthType(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedRows.value = selection.map((item) => item)
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  getList()
}

/** 确认 */
const submitAuth = async () => {
  //判断参数是否有效
  let authType = queryParams.authType || ''
  let authUserId = form.value.authUserId || ''

  console.info(authType + ':' + selectedRows + ':' + authUserId)
  if (authType == '' || selectedRows.value.length == 0 || authUserId == '') {
    message.error('管理人员或者授权的区域不能为空')
    return false
  }
  let authAddrIdArr = []
  selectedRows.value.forEach((e, i) => {
    authAddrIdArr.push(e.addrId)
  })
  form.value = {
    authType: authType,
    userType: form.value.userType,
    authUserId: authUserId,
    authUserName: form.value.authUserName,
    authAddrIds: authAddrIdArr
  }
  // 添加的提交
  const formData = form.value as unknown as AuthAddrApi.AuthAddrVo
  AuthAddrApi.createAuthAddr(formData).then((data) => {
    message.success(t('common.createSuccess'))
    emits('comfirmAuthAddr')
    dialogVisible.value = false
  })
}

const selectMemberRef = ref()
const openSelectMember = () => {
  //判断是否选择了社区，后台需要判断集中器所在的社区和电表所在的社区是否一致
  selectMemberRef.value.open()
}

const confirmMemberUser = (memberUser) => {
  form.value.authUserId = memberUser.id
  form.value.authUserName = memberUser.nickname
  form.value.userType = 1
}

const sysUserSelectRef = ref()
const openSelectSys = () => {
  //判断是否选择了社区，后台需要判断集中器所在的社区和电表所在的社区是否一致
  sysUserSelectRef.value.open()
}
const confirmSysUser = (sysUser) => {
  form.value.authUserId = sysUser.id
  form.value.authUserName = sysUser.nickname
  form.value.userType = 2
}
const clearUser = () => {
  form.value.authUserId = undefined
  form.value.authUserName = undefined
}
</script>
